package com.yzt.dynamicmodule.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.yzt.p_base.utils.ThreadCenter;
import com.yzt.plugin_imageloader.ImageLoadUtil;
import com.yzt.plugin_widget.RoundImageView;
import com.yzt.zhuju.arouter.RouterDynamic;
import com.yzt.zhuju.dialog.BaseDialog;
import com.yzt.zhuju.dialog.DynamicSelectDialog;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.user.RefreshDynamicEvent;
import com.yzt.zhuju.mvp.MVPActivity;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.sysConfig.AliOSSCredentialBean;
import com.yzt.zhuju.network.entity.sysConfig.ReportPhotoBean;
import com.yzt.zhuju.photoview.PhotoViewManager;
import com.yzt.zhuju.utils.AppDialogUtil;
import com.yzt.zhuju.utils.DefaultCropFileEngine;
import com.yzt.zhuju.utils.GlideImageEngine;
import com.yzt.zhuju.utils.ImageUpLoadUtils;
import com.yzt.zhuju.utils.McImageCompressEngine;
import com.yzt.zhuju.utils.map.BdLocationUtil;
import com.yzt.dynamicmodule.R;
import com.yzt.dynamicmodule.adapter.DynamicAddImgAdapter;
import com.yzt.dynamicmodule.contacts.AddDynamicContacts;
import com.yzt.dynamicmodule.presenter.AddDynamicPresenter;
import com.yzt.p_base.AppUtils;
import com.yzt.p_base.utils.DisplayUtils;

import java.util.ArrayList;
import java.util.List;

import com.yzt.p_base.utils.ToastUtil;
import com.yzt.zhuju.widget.tuiview.TUITextView;

import io.rong.imkit.picture.decoration.GridSpacingItemDecoration;

/**
 * author : bob
 * date   : 2023/2/27
 * desc   : 新增动态
 */
@SuppressLint("SetTextI18n")
@Route(path = RouterDynamic.ACTIVITY_DYNAMIC_ADD)
public class DynamicAddActivity extends MVPActivity<AddDynamicPresenter> implements AddDynamicContacts.View {

    @Autowired
    int extra_type = 0;

    @Autowired
    String extra_path = "";

    @Autowired
    ArrayList<String> extra_list_path;

    private LatLng latLng;

    public final static int SPAN_COUNT = 5;

    private EditText tvTitle;

    private EditText tvContent;

    private RoundImageView imgCover;

    private TextView tvAddress;

    private RecyclerView recyclerView;

    private TUITextView tvPub;
    private RelativeLayout rlProgress;
    private ProgressBar mineProgress;
    private TextView tvProgress;

    private DynamicAddImgAdapter mAdapter;

    private AliOSSCredentialBean aliOSSCredentialBean;

    private final List<ReportPhotoBean> mPhotoArray = new ArrayList<>();

    private String latitudeValue;

    private String longitudeValue;

    private String cityCode;

    private String city;

    private String videoPath;

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_dynamic;
    }

    @Override
    public void installViews() {
        mTitleBar.setTitle("");
        tvPub = findViewById(R.id.tv_pub);
        tvPub.setOnClickListener(this);
        tvTitle = findViewById(R.id.tv_title);
        tvContent = findViewById(R.id.tv_content);
        imgCover = findViewById(R.id.img_cover);
        imgCover.setOnClickListener(this);
        tvAddress = findViewById(R.id.tv_address);
        tvAddress.setOnClickListener(this);
        recyclerView = findViewById(R.id.recycler_view);
        rlProgress = findViewById(R.id.rl_progress);
        mineProgress = findViewById(R.id.mine_progress);
        tvProgress = findViewById(R.id.tv_progress);

        // 加载定位
        initPermission();

        initPhotoView();

        getAliSign();

        loadExt();
    }

    private void loadExt() {
        if (extra_type == 0) {
            // 视频
            videoPath = extra_path;
            ImageLoadUtil.loadImg(DynamicAddActivity.this, videoPath, imgCover);
            recyclerView.setVisibility(View.GONE);
            imgCover.setVisibility(View.VISIBLE);
            tvPub.setText("发布视频");
        }
        if (extra_type == 1) {
            // 拍照
            List<ReportPhotoBean> photoList = mAdapter.getData();
            //String picturePath = extra_path;
            // TODO: 2024/1/30
            for(String path :extra_list_path){
                ReportPhotoBean photo = new ReportPhotoBean(1, path, path);
                photoList.add(photo);
            }
            mAdapter.notifyDataSetChanged();
            delPhotoCal();
            recyclerView.setVisibility(View.VISIBLE);
            imgCover.setVisibility(View.GONE);
            tvPub.setText("发布图文");
        }
    }

    /**
     * 权限初始化
     */
    private void initPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {
                // 方法帮助应用判断是否需要向用户解释为什么需要某个权限，并在适当的时候进行解释和再次请求。
            } else {
                //请求权限
                int MY_PERMISSIONS_REQUEST_LOCATION = 9999;
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
        } else {
            // 权限满足
            initLocationOption();
        }
    }

    /**
     * 获取定位信息
     */
    private void initLocationOption() {

        if (!checkGPSIsOpen(mActivity)) {
            ToastUtil.showMessage("请打开GPS定位服务");
        }

        BdLocationUtil.getInstance().requestLocation(new BdLocationUtil.MyLocationListener() {
            @Override
            public void myLocation(BDLocation location) {
                latLng = BdLocationUtil.bd2gd(location.getLatitude(), location.getLongitude());
                latitudeValue = latLng.latitude + "";
                longitudeValue = latLng.longitude + "";
                cityCode = location.getCityCode();
                city = location.getCity();
                tvAddress.setText(city);
            }
        });
    }

    public static boolean checkGPSIsOpen(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return gps || network;
    }

    /**
     * 获取 ali oss 签名信息
     */
    public void getAliSign() {
        BizLayer.getInstance().getSystemModule().getAliSign(new AresSubscriber<AliOSSCredentialBean>() {
            @Override
            protected void onSuccess(AliOSSCredentialBean data) {
                aliOSSCredentialBean = data;
                ImageUpLoadUtils.getInstance().init(DynamicAddActivity.this, aliOSSCredentialBean);
                Log.e("", "TeacherRegisterPresenterImpl-->我获得了ali签名信息");
            }
        });
    }

    /**
     * 初始化照片列表
     */
    private void initPhotoView() {

        recyclerView.setLayoutManager(new GridLayoutManager(mActivity, SPAN_COUNT));
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(SPAN_COUNT, DisplayUtils.dp2px(SPAN_COUNT), false));
        mAdapter = new DynamicAddImgAdapter();
        recyclerView.setAdapter(mAdapter);
        mAdapter.addData(new ReportPhotoBean(-1, "", ""));
        mAdapter.addChildClickViewIds(R.id.delete_iv);
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.delete_iv) {
                AppDialogUtil.showNoTitleDialog(mActivity, mActivity.getString(R.string.str_delete_photo), mActivity.getString(R.string.cancel), mActivity.getString(R.string.delete), new AppDialogUtil.DialogClickInterface() {
                    @Override
                    public void onCancelClick() {

                    }

                    @Override
                    public void onSureClick() {
                        mAdapter.remove(position);
                        List<ReportPhotoBean> photoList = mAdapter.getData();
                        ReportPhotoBean reportPhotoEntry = photoList.get(0);
                        if (reportPhotoEntry.getStatus() != -1) {
                            mAdapter.addData(new ReportPhotoBean(-1, "", ""));
                        }
                        delPhotoCal();
                    }
                });
            }
        });

        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            ReportPhotoBean itemLayoutEntry = (ReportPhotoBean) adapter.getData().get(position);
            if (itemLayoutEntry.getStatus() == -1) {//拍照
                DynamicSelectDialog dialog = (DynamicSelectDialog) BaseDialog.showDialog(this, DynamicSelectDialog.class);
                dialog.setListener(new DynamicSelectDialog.OnSelectOnClickListener() {

                    @Override
                    public void onSelectVideo() {
                        selectImage(2);
                    }

                    @Override
                    public void onSelectPic() {
                        if (mPhotoArray.size() >= 3) {
                            ToastUtil.showMessage(getString(R.string.dynamic_max_select_pic_size_nine));
                            return;
                        }

                        selectImage(1);
                    }
                });
            } else {  //查看
                List<ReportPhotoBean> dataList = (List<ReportPhotoBean>) adapter.getData();
                List<String> list = new ArrayList<>();
                for (ReportPhotoBean entry : dataList) {
                    if (!TextUtils.isEmpty(entry.getPathUrl())) {
                        list.add(entry.getPathUrl());
                    }
                }
                PhotoViewManager.getInstance(AppUtils.getApp()).showPhotoView(view, list, position);
            }
        });
    }

    /**
     * 选择图片
     */
    private void selectImage(int type) {
        if (type == 1) {
            PictureSelector.create(mActivity)
                    .openGallery(SelectMimeType.ofImage())
                    .setImageEngine(GlideImageEngine.Companion.getInstance())
                    .setCompressEngine(McImageCompressEngine.Companion.getInstance())
                    .setCropEngine(new DefaultCropFileEngine())
                    .setMaxSelectNum(3 - mPhotoArray.size())
                    .isDirectReturnSingle(true)
                    .isDisplayCamera(false)
                    .isOpenClickSound(false)
                    .isFastSlidingSelect(true)
                    .isPreviewFullScreenMode(true)
                    .isPreviewZoomEffect(true)
                    .isPreviewImage(true)
                    .isMaxSelectEnabledMask(true)
                    .isGif(false)
                    .forResult(PictureConfig.CHOOSE_REQUEST);
        } else {
            PictureSelector.create(mActivity)
                    .openGallery(SelectMimeType.ofVideo())
                    .setImageEngine(GlideImageEngine.Companion.getInstance())
                    .setCompressEngine(McImageCompressEngine.Companion.getInstance())
                    .setCropEngine(new DefaultCropFileEngine())
                    .setMaxVideoSelectNum(1)
                    .setFilterVideoMaxSecond(60)
                    .isDirectReturnSingle(true)
                    .isDisplayCamera(false)
                    .isOpenClickSound(false)
                    .isFastSlidingSelect(true)
                    .isPreviewFullScreenMode(true)
                    .isPreviewZoomEffect(true)
                    .isPreviewImage(true)
                    .isMaxSelectEnabledMask(true)
                    .forResult(PictureConfig.CHOOSE_REQUEST);
        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.tv_address) {
            // 选择地址
            Intent intent = new Intent(mActivity, GameAddCityActivity.class);
            intent.putExtra("extra_id", city);
            intent.putExtra("extra_latitude", latLng.latitude);
            intent.putExtra("extra_longitude", latLng.longitude);
            startActivityForResult(intent, 3);
        } else if (view.getId() == R.id.tv_cancel) {
            // 取消
            finish();
        } else if (view.getId() == R.id.tv_pub) {
            // 发布
            addNewDynamic();
        } else if (view.getId() == R.id.img_cover) {
            // 视频
            selectImage(2);
        }
    }

    /**
     * 新增动态
     */
    private void addNewDynamic() {

        String content = tvContent.getText().toString();
        String title = tvTitle.getText().toString();

        if (title.equals("")) {
            ToastUtil.showMessage("说输入标题～");
            return;
        }

        if (content.equals("")) {
            ToastUtil.showMessage("请输入内容～");
            return;
        }

        if (aliOSSCredentialBean == null) {
            runOnUiThread(() -> {
                showToast("获取照片签名异常，请重新选择照片");
                getAliSign();
            });
            return;
        }

        showMProgress();

        List<String> urlList1 = new ArrayList<>();

        if (!mPhotoArray.isEmpty()) {
            // 发布图文动态
            for (ReportPhotoBean bean : mPhotoArray) {

                String time = System.currentTimeMillis() + ".png";

                ImageUpLoadUtils.getInstance().asyncUpLoad(time, bean.getPathUrl(), new ImageUpLoadUtils.OnAsyncUpLoadListener() {

                    @Override
                    public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

                    }

                    @Override
                    public void onSuccess(PutObjectRequest request, PutObjectResult result, String directory) {
                        ThreadCenter.postUITask(new Runnable() {
                            @Override
                            public void run() {
                                urlList1.add(directory + request.getObjectKey());
                                if (urlList1.size() == mPhotoArray.size()) {
                                    publish(urlList1);
                                }
                                tvPub.setVisibility(View.GONE);
                                rlProgress.setVisibility(View.VISIBLE);
                                mineProgress.setProgress(urlList1.size() * 100 / mPhotoArray.size());
                                tvProgress.setText("发布中..." + (urlList1.size() * 100 / mPhotoArray.size()) + "%");
                            }
                        });
                    }

                    @Override
                    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                        showToast("上传失败");
                        closeProgress();
                    }
                });
            }
            return;
        }
        if (videoPath != null) {
            // 发布视频动态
            String time = System.currentTimeMillis() + ".mp4";

            ImageUpLoadUtils.getInstance().asyncUpLoad(time, videoPath, new ImageUpLoadUtils.OnAsyncUpLoadListener() {

                @Override
                public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                    ThreadCenter.postUITask(new Runnable() {
                        @Override
                        public void run() {
                            tvPub.setVisibility(View.GONE);
                            rlProgress.setVisibility(View.VISIBLE);
                            mineProgress.setProgress((int) (currentSize * 100 / totalSize));
                            tvProgress.setText("发布中..." + (int) (currentSize * 100 / totalSize) + "%");
                        }
                    });
                }

                @Override
                public void onSuccess(PutObjectRequest request, PutObjectResult result, String directory) {
                    urlList1.add(directory + request.getObjectKey());
                    publish(urlList1);
                }

                @Override
                public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                    showToast("上传失败");
                    closeProgress();
                }
            });
        } else {
            publish(urlList1);
        }
    }

    /**
     * 发布动态
     */
    private void publish(List<String> urlList1) {
        String content = tvContent.getText().toString();
        String title = tvTitle.getText().toString();
        JSONObject json = new JSONObject();
        json.put("bgColor", "#FFFFFF");
        json.put("title", title);
        json.put("content", content);
        // 动态类型 图文，视频，纯文本 [ 1：图片，2：视频，3：纯文本 ]
        if (!mPhotoArray.isEmpty()) {
            json.put("contentType", 1);
        }
        if (videoPath != null) {
            json.put("contentType", 2);
        }
        if (!urlList1.isEmpty()) {
            json.put("contentUrlList", urlList1);
        }
        json.put("cityCode", cityCode);
        json.put("lat", latitudeValue);
        json.put("lon", longitudeValue);
        String location = tvAddress.getText().toString();
        json.put("location", location);

        mPresenter.publicDynamic(json);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_CANCELED) {
            return;
        }

        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            if (data != null) {
                List<ReportPhotoBean> photoList = mAdapter.getData();
                ArrayList<LocalMedia> result = PictureSelector.obtainSelectorList(data);
                if (result.get(0).getRealPath().endsWith("mp4") || result.get(0).getRealPath().endsWith("MP4")) {
                    videoPath = result.get(0).getRealPath();
                    ImageLoadUtil.loadImg(DynamicAddActivity.this, videoPath, imgCover);
                    recyclerView.setVisibility(View.GONE);
                    imgCover.setVisibility(View.VISIBLE);
                    return;
                }

                recyclerView.setVisibility(View.VISIBLE);
                imgCover.setVisibility(View.GONE);
                for (LocalMedia bean : result) {
                    String picturePath = bean.getRealPath();
                    ReportPhotoBean photo = new ReportPhotoBean(1, picturePath, picturePath);
                    photoList.add(photo);
                }
                mAdapter.notifyDataSetChanged();
            }
            delPhotoCal();
        }

        if (requestCode == 3 && resultCode == RESULT_OK) {
            PoiInfo bean = data.getParcelableExtra("extra_data");
            latitudeValue = bean.getLocation().latitude + "";
            longitudeValue = bean.getLocation().longitude + "";
            tvAddress.setText(bean.getName());
        }
    }

    public void delPhotoCal() {
        mPhotoArray.clear();
        for (ReportPhotoBean file : mAdapter.getData()) {
            if (file.getStatus() != -1) {
                mPhotoArray.add(new ReportPhotoBean(1, file.getPathUrl(), file.getPathUrl()));
            }
        }
    }

    @Override
    public void publishSuccess() {
        ToastUtil.showMessage(getString(R.string.dynamic_publish_success));
        RxBus.getDefault().post(new RefreshDynamicEvent());
        finish();
    }

    @Override
    public void publishEnd() {
        dismissLoadingDialog();
    }
}